package com.acme.bankapp.service.bank;

import java.io.FileReader;
import java.util.Scanner;

import com.acme.bankapp.domain.bank.Account;
import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.CheckingAccount;
import com.acme.bankapp.domain.bank.SavingsAccount;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.domain.bank.Gender;
import com.acme.bankapp.service.bank.BankService;

public class BankDataLoaderService {
	
	@SuppressWarnings("serial")
	public static class FeedLoadException extends Exception {

	}
	
	public static void feedLoadBank(Bank bank, String fileName) throws FeedLoadException {
		Scanner scanner = null;
		try {
			scanner = new Scanner(new FileReader(fileName));
			while (scanner.hasNextLine()) clientFromString(bank, scanner.nextLine());
		} catch (Exception e) {
			throw new FeedLoadException();
		} finally {
			if (scanner != null) scanner.close();
		}
	}
    
    public static void clientFromString(Bank bank, String string) throws FeedLoadException {
        String[] parts = string.split(";");
        try {
        	double balance = getValue(parts[1]);
        	double overdraft = getValue(parts[2]);
        	String name = getName(parts[3]);
        	Gender gender = getGender(parts[4]);
        	Account account = getAccount(parts[0], balance, overdraft);
        	Client client = new Client(name, gender, account);
        	BankService.addClient(bank, client);
        } catch (Exception e) {
        	throw new FeedLoadException();
        }
    }
    
    private static String getName(String string) throws FeedLoadException {
    	String[] parts = string.split("=");
    	try {
    		return parts[1];
    	} catch (Exception e) {
    		throw new FeedLoadException();
    	}
    }    
        
    
    private static double getValue(String string) throws FeedLoadException {
    	String[] parts = string.split("=");
    	try {
    		return Double.valueOf(parts[1]);
    	} catch (Exception e) {
    		throw new FeedLoadException();
    	}
    }    
    
    private static Gender getGender(String string) throws FeedLoadException {
    	String[] parts = string.split("=");
    	try {
    		if (parts[1].charAt(0) == 'm') {
    			return Gender.MALE;
    		} else if (parts[1].charAt(0) == 'f') {
    			return Gender.FEMALE;
    		} else {
    			throw new FeedLoadException();
    		}
    	} catch (Exception e) {
    		throw new FeedLoadException();
    	}
    }
    
    private static Account getAccount(String string, double balance, double overdraft) throws FeedLoadException {
    	String[] parts = string.split("=");
    	try {
    		if (parts[1].charAt(0) == 'c') {
    			return new CheckingAccount(balance, overdraft);
    		} else if (parts[1].charAt(0) == 's') {
    			return new SavingsAccount(balance);
    		} else {
    			throw new FeedLoadException();
    		}
    	} catch (Exception e) {
    		throw new FeedLoadException();
    	}
    }    
}
